<template>
  <div>
    <el-upload
        action=""
        class="upload-demo"
        :http-request="handleUpload"
        :on-remove="handleRemove"
        :on-error="handleError"
        :file-list="fileList"
        list-type="picture"
        :before-upload="handleBeForUpload"
        :limit="limit"
        :on-exceed="uploadOverRun"
        :on-preview="handlePictureCardPreview"
        :on-progress="handleProgress"
    >
      <el-button size="small" type="primary" >点击上传</el-button>
    </el-upload>
<!--    <p> {{  }}</p>-->
    <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"  ></el-progress>
  </div>
</template>

<script>

import tool from './oss'

export default {
  props: {
    value: {
      type: String
    },
    fileListStr: {
      type: String
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      percentage: 0,
      dialogImageUrl: '',
      dialogVisible: false,
      images: [],
      fileList: [],
    }
  },
  watch: {
    value ( newValue, oldValue) {
      this.fillFileList( newValue );
    }
  },
  created() {
    if (this.value) {
      this.fillFileList( this.value )
    }
  },
  methods: {
    fillFileList( value  ){
      let fileListTemp = [];
      let tempArray =  value =='' ? [] : JSON.parse(  value  );
      tempArray.forEach(element => {
        fileListTemp.push( {
          name : element.name ,
          url:  element.url
        } )
      });
      this.fileList = fileListTemp ;
    },
    //自定义上传
    async handleUpload( value ){
      // const data = this.getDate();
      console.log(value)
      tool.oss.onProgress = this.handleProgress; // 设置进度回调
      let res = await tool.oss.upload( value.file , value.file.name )
      if (res.res.status === 200){
        this.fileList.push({
          name: value.file.name,
          url: res.res.requestUrls[0]
        })
        this.$emit('input',  JSON.stringify( this.fileList )  )
      }
    },
    //移除文件的钩子
    handleRemove(file, fileList){
      let tempArray =  this.value==='' ? [] : JSON.parse(  this.value  );
      let valueList = tempArray.map(item => item.url )
      for (var i = 0; i < valueList.length; i++) {
        // 存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        let url
        // 后台已有照片
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.path
        }
        if (url.includes(valueList[i])) {
          tempArray.splice(i)
        }
      }
      this.$emit('input', JSON.stringify(tempArray))

    },
    //上传成功的钩子
    handleSuccess(res,file, fileList){
      console.log(res,"res")
      console.log(file,"file")
      console.log(fileList,"fileList")
      // res.data = JSON.parse(CryptoJS.Decrypt(res.data))
      // let tempArray =  this.value=='' ? [] : JSON.parse(  this.value  );
      if (fileList.every(item => item.status == 'success')) {
        fileList.map(item => {
          console.log( item );
          if(item.response) {
            this.fileList.push({
              name: item.name,
              url: item.response.data.path
            })
          }
        })
      }
      setTimeout(() => {
        this.$emit('input',  JSON.stringify( this.fileList )  )
      }, 500);
    },
    //上传失败的钩子
    handleError(){
      this.$message({ message: '上传失败', type: 'error' })
    },
    //文件超出个数限制时的钩子
    uploadOverRun(){
      this.$message({
        type: 'error',
        message: '上传文件个数超出限制!'
      })

    },
    //点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(){

    },
    //文件上传时的钩子
    handleProgress(p){
      // console.log(p ,"")
      this.percentage = parseFloat(p.toFixed(2));
    },
    handleBeForUpload(){
      this.percentage = 0 ;
      console.log(this.value)
    },

    getDate(){
      const date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const second = String(date.getSeconds()).padStart(2, '0')
      month = month > 9 ? month : '0' + month
      day = day < 10 ? '0' + day : day
      var today = year + month + day +hours + minutes+second
      return today
    },



  }
}
</script>